package learn.spring.disruptor;

import java.util.concurrent.ThreadFactory;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;

/**
 * 配置
 * 
 * @author PinWei Wan
 * @since 2.6.9
 */
@Configuration
public class Config {

    @Bean
    @SuppressWarnings("unchecked")
    public RingBuffer<MessageModel> messageModelRingBuffer() {
        // 定义用于事件处理的线程池，
        ThreadFactory threadFactory = new CustomizableThreadFactory("disruptor-pool-");

        // 指定事件工厂
        MessageEventFactory factory = new MessageEventFactory();

        // 指定ringbuffer字节大小，必须为2的N次方（能将求模运算转为位运算提高效率），否则将影响效率
        int bufferSize = 1024 * 256;

        Disruptor<MessageModel> disruptor = new Disruptor<>(factory, bufferSize, threadFactory);

        // 设置事件业务处理器---消费者
        disruptor.handleEventsWith(new MessageConsumer(), new MessageConsumer());

        // 启动disruptor线程
        disruptor.start();

        // 获取ringbuffer环，用于接取生产者生产的事件
        RingBuffer<MessageModel> ringBuffer = disruptor.getRingBuffer();

        return ringBuffer;
    }
}
